package com.hljx.config;

import com.hljx.config.constant.StaticConstant;
import com.hljx.filter.CommonMethod;
import com.hljx.utils.EncodeUtils;
import com.hljx.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;

import java.io.IOException;

/**
 * @BelongsProject: hljx
 * @BelongsPackage: com.hljx.config
 * @Author: lp
 * @CreateTime: 2023-12-21  09:55
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@ComponentScan
@WebFilter(filterName = "httpServletRequestWrapperFilter", urlPatterns = {"/*"})
@Order(0)
public class HttpServletRequestWrapperFilter  implements Filter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private CommonMethod commonMethod;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("doFilter");
        ServletRequest requestWrapper = null;

        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            //遇到post方法才对request进行包装
            String methodType = httpRequest.getMethod();
            String servletPath = httpRequest.getRequestURI();
            if ("POST".equals(methodType)&&!servletPath.contains("/etlItemImport/importExcel")) {
                requestWrapper = new MyRequestWrapper(
                        (HttpServletRequest) request);
            }
            String authToken = httpRequest.getHeader(this.tokenHeader);
            if (authToken != null) {
                String userCode = jwtTokenUtil.getUserNameFromToken(authToken);
                log.info("checking userCode:{}", userCode);
                if (userCode != null) {
                    if (jwtTokenUtil.validateToken(authToken, userCode)) {
                        log.info("authenticated user:{}", userCode);
                    }
                }
            }
            if (StringUtils.isNotBlank(httpRequest.getHeader(StaticConstant.USER_NAME))) {
                commonMethod.setUserName(EncodeUtils.urlDecode(httpRequest.getHeader(StaticConstant.USER_NAME)));
            }
            commonMethod.setUserCode(httpRequest.getHeader(StaticConstant.USER_CODE));
        }
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
        //防止线程内存溢出，清除线程变量
        commonMethod.clear();
    }


    @Override
    public void destroy() {

    }
}
